package cn.nit.algorithm.experiment;

/**
 * 试验一：统计求最大、最小元素的平均比较次数
 *
 * 编写一个程序，随机产生10个1~20的整数，设计一个高效算法找其中的最大元素和最小
 * 元素，并统计元素之间的比较次数。调用该算法执行10次并求元素的平均比较次数。
 */

import java.util.ArrayList;
import java.util.Random;

public class Experiment1 {
    private ArrayList<Integer> list = new ArrayList();
    private int length;
    private int max;
    private int min;
    private int compareNum = 0;
    public String totalString="";

    //寻找最大值与最小值并返回比较次数
    private int findMaxAndMin() {
        compareNum = 0;
        max = min = list.get(0);
        for (int i = 1; i < list.size(); i++) {
            if (list.get(i) < min) {
                min = list.get(i);
                compareNum++;
                continue;
            } else if (list.get(i) > max) {
                max = list.get(i);
                compareNum++;
                continue;
            } else {
                compareNum += 2;
            }
        }
        return compareNum;
    }

    //初始化改list，并执行寻找最大值最小值方法，并返回比较次数
    public int initAListAndRunFind() {
        list = new ArrayList<>();
        Random random = new Random();
        for (int i = 0; i < 10; i++) {
            int temp = random.nextInt(20) + 1;
            list.add(temp);
            System.out.print(temp + "  ");
            totalString += temp + "  ";
        }
        System.out.println();
        totalString += "<br>";
        length = list.size();

        int number = findMaxAndMin();
        System.out.println("最大数为：" + max + "最小数为：" + min);
        totalString += "最大数为：" + max + "最小数为：" + min+"<br>";
        System.out.println("比较次数为：" + number);
        totalString += "比较次数为：" + number+"<br>";
        return number;
    }

//    public static void main(String[] args) {
//        Experiment1 experiment1 = new Experiment1();
//        //执行十次并求出平均比较次数并输出
//        double avNumber = 0;
//        for (int i = 0; i < 10; i++) {
//            avNumber += experiment1.initAListAndRunFind();
//        }
//        System.out.println("平均比较次数：" + avNumber / 10);
//        experiment1.totalString += "平均比较次数：" + avNumber / 10+"<br>";
//    }

    public String runMain(){
        Experiment1 experiment1 = new Experiment1();
        //执行十次并求出平均比较次数并输出
        double avNumber = 0;
        for (int i = 0; i < 10; i++) {
            avNumber += experiment1.initAListAndRunFind();
        }
        System.out.println("平均比较次数：" + avNumber / 10);
        experiment1.totalString += "平均比较次数：" + avNumber / 10+"<br>";
        return experiment1.totalString;
    }
}
